package com.ruoyi.app.business.message;

import cn.hutool.core.collection.CollUtil;
import com.ruoyi.app.config.platform.PlatFormConfig;
import com.ruoyi.app.config.util.UserUtil;
import com.ruoyi.app.converter.MessageConverter;
import com.ruoyi.app.domain.message.MessageContent;
import com.ruoyi.app.domain.message.MessageDetail;
import com.ruoyi.app.domain.message.MessageSimple;
import com.ruoyi.app.domain.message.properties.PropertiesExpend;
import com.ruoyi.common.core.enums.YesNoEnum;
import com.ruoyi.common.core.utils.CommonUtils;
import com.ruoyi.common.core.utils.LocalDateUtils;
import com.ruoyi.common.core.utils.PageUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.page.CommonPageInfo;
import com.ruoyi.service.company.service.CompanyService;
import com.ruoyi.service.message.entity.UserMessageEntity;
import com.ruoyi.service.message.enums.MessageTemplateEnum;
import com.ruoyi.service.message.query.MessageBaseQuery;
import com.ruoyi.service.message.service.UserMessageService;
import com.ruoyi.service.project.entity.ProjectEntity;
import com.ruoyi.service.project.service.ProjectService;
import com.ruoyi.service.score.entity.CompanyScoreDetailEntity;
import com.ruoyi.service.score.entity.LaborScoreDetailEntity;
import com.ruoyi.service.score.service.CompanyScoreDetailService;
import com.ruoyi.service.score.service.CompanyScoreService;
import com.ruoyi.service.score.service.LaborScoreDetailService;
import com.ruoyi.service.score.service.LaborScoreService;
import com.ruoyi.service.user.entity.UserEntity;
import com.ruoyi.service.user.service.UserService;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * <p>
 * 作用：消息业务类
 * </p>
 *
 * @author Zane
 * @since 2025-10-25 1:22
 */
@Component
public class MessageBusiness {

  @Resource
  private UserMessageService userMessageService;
  @Resource
  private UserService userService;
  @Resource
  private PlatFormConfig platFormConfig;
  @Autowired
  private ProjectService projectService;
  @Autowired
  private CompanyService companyService;
  @Autowired
  private LaborScoreService laborScoreService;
  @Autowired
  private CompanyScoreService companyScoreService;
  @Autowired
  private CompanyScoreDetailService companyScoreDetailService;
  @Autowired
  private LaborScoreDetailService laborScoreDetailService;

  public void addMessage(MessageTemplateEnum template, Map<String, String> properties,
      String traceId, Long targetUser, String sender, Long contactId) {
    final UserEntity userInfo = userService.getById(contactId);
    addMessage(Collections.singletonList(targetUser), template.getTopic(),
        template.getMessage(properties), template.getCode(), traceId,
        sender, userInfo.getName(), userInfo.getPhone());
  }

  public void addMessage(MessageTemplateEnum template, Map<String, String> properties,
      String traceId, List<Long> targetUsers, String sender, Long contactId) {
    final UserEntity userInfo = userService.getById(contactId);
    addMessage(targetUsers, template.getTopic(), template.getMessage(properties),
        template.getCode(), traceId, sender, userInfo.getName(), userInfo.getPhone());
  }

  public void sendPlatformMsg(MessageTemplateEnum template, Map<String, String> properties,
      String traceId,
      Long userId) {
    addMessage(userId, template.getTopic(), template.getMessage(properties),
        template.getCode(), traceId, platFormConfig.getName(),
        platFormConfig.getLinkUser(),
        platFormConfig.getPhone());
  }

  public void addMessage(Long targetUser, String topic, String content, String type, String traceId,
      String sender, String contactName, String contactPhone) {
    addMessage(Collections.singletonList(targetUser),
        topic, content, type, traceId, sender, contactName, contactPhone);
  }

  // 消息列表
  public void addMessage(List<Long> targetUserList, String topic, String content, String type,
      String traceId,
      String sender,
      String contactName,
      String contactPhone) {
    if (CollUtil.isEmpty(targetUserList)) {
      return;
    }
    List<UserMessageEntity> saveList = CollUtil.newArrayList();
    targetUserList.forEach(targetUserId -> {
      saveList.add(new UserMessageEntity()
          .setUserId(targetUserId)
          .setContent(content)
          .setType(type)
          .setTraceId(traceId)
          .setTopic(topic)
          .setSender(sender)
          .setContactName(contactName)
          .setContactPhone(contactPhone)
          .setCheckFlag(YesNoEnum.NO.getCode())
          .setCreateBy(platFormConfig.getId())
          .setCreateTime(LocalDateTime.now())
          .setUpdateBy(platFormConfig.getId())
          .setUpdateTime(LocalDateTime.now()));
    });
    userMessageService.saveBatch(saveList);
  }

  // 消息列表
  public CommonPageInfo<MessageSimple> messageList(MessageBaseQuery query) {
    final CommonPageInfo<UserMessageEntity> page = PageUtils.startPage(query.getPageNum(),
        query.getPageSize());
    page.initData(userMessageService.queryList(query, UserUtil.getUserId()));
    return page.convert(MessageConverter.INSTANCE::toSimple);
  }

  public MessageDetail messageDetail(Long messageId) {
    final UserMessageEntity messageInfo = CommonUtils.requireNotNull(
        userMessageService.getByIdAndUserId(messageId, UserUtil.getUserId()),
        "您无该消息");
    final MessageDetail detail = MessageConverter.INSTANCE.toDetail(messageInfo)
        .setContent(buildContent(messageInfo));
    return detail;
  }

  private MessageContent buildContent(UserMessageEntity messageInfo) {
    final MessageTemplateEnum messageTemplate = MessageTemplateEnum.valueOf(messageInfo.getType());
    switch (messageTemplate.getType()) {
      case PROJECT_MSG: {
        final String projectId = messageInfo.getTraceId();
        if (StringUtils.isNotBlank(projectId)) {
          final ProjectEntity project = projectService.getById(projectId);
          final String companyName = companyService.getNameById(project.getComId());
          return newContent(project.getProjectName(), companyName, messageInfo.getContent());
        }
      }
      case EVALUATION_MSG: {
        final String traceId = messageInfo.getTraceId();
        if (MessageTemplateEnum.A18 == messageTemplate) {
          //项目方获得评
          final CompanyScoreDetailEntity detail = companyScoreDetailService.getById(traceId);
          return newProjectContent(detail.getProjectId(), detail.getRemark());
        } else {
          final LaborScoreDetailEntity scoreDetail = laborScoreDetailService.getById(traceId);
          return newProjectContent(scoreDetail.getProjectId(), scoreDetail.getRemark());
        }
      }
      default:
        return new MessageContent();
    }
  }

  private MessageContent newProjectContent(final String projectId, String content) {
    final ProjectEntity project = projectService.getById(projectId);
    final String companyName = companyService.getNameById(project.getComId());
    return newContent(project.getProjectName(), companyName, content);
  }

  private MessageContent newContent(String projectName, String companyName, String content) {
    return new MessageContent()
        .setProjectName(projectName)
        .setCompanyName(companyName)
        .setContent(content);
  }

  public void messageCheck(Long messageId) {
    final UserMessageEntity messageInfo = CommonUtils.requireNotNull(
        userMessageService.getByIdAndUserId(messageId, UserUtil.getUserId()),
        "您无该消息");
    messageInfo.setCheckFlag(YesNoEnum.YES.getCode())
        .setUpdateBy(UserUtil.getUserId())
        .setUpdateTime(LocalDateTime.now());
    userMessageService.updateById(messageInfo);
  }

  public Map<String, String> buildProjectProperties(ProjectEntity project,
      PropertiesExpend... expends) {

    return new HashMap<String, String>() {{
      put("projectName", project.getProjectName());
      put("projectEndTime", LocalDateUtils.dateTimeFormat(project.getProjectEnd()));
      if (Objects.nonNull(expends)) {
        for (PropertiesExpend expend : expends) {
          put(expend.getKey(), expend.getValue());
        }
      }
    }};
  }

  public Long unreadCount() {
    return  userMessageService.unreadCount(UserUtil.getUserId());
  }
}
